package com.wnxy.carl.commons;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    //设置令牌
    public static final String AUTH_TOKEN_NAME = "auth_token";

    /**
     * 签名用的密钥
     */

    private static String SIGNING_KEY = "78sebr72umyz33i9876gc31urjgyfhgj";

    public static final String USER_ID_KEY = "userId";
    public static final String STORE_ID_KEY = "storeId";
    public static final String USER_NAME_KEY = "userName";
    public JwtUtils(String signingKey){
        this.SIGNING_KEY=signingKey;
    }
    //封装jwt
    public static String createJWT(Integer expirationTime, Map<String, Object> payload) {
        long expiration = expirationTime * 60 * 1000L;
        return create(expiration,payload);
    }
    //封装jwt只要一个userId
    public static String createJwtByUserId(Integer expirationTime, Integer userId) {
        Map<String,Object> payload = new HashMap<>();
        payload.put(USER_ID_KEY,userId);
        return createJWT(expirationTime,payload);
    }
    //封装jwt(用户id和门店id)userId，storeId
    public static String createJwtByUserId(Integer expirationTime, Integer userId,Integer storeId) {
        Map<String,Object> payload = new HashMap<>();
        payload.put(USER_ID_KEY,userId);
        payload.put(STORE_ID_KEY,storeId);
        return createJWT(expirationTime,payload);
    }
    //解析jwt
    public static Claims parseJWT(String token){
        System.out.println("token:"+token);
        Claims claims = parse(token);
        return claims;
    }
    //解析jwt只要一个UserId
    public static Integer parseJwtByUserId(String token){
        Claims claims = parse(token);
        Integer userId = (Integer) claims.get(USER_ID_KEY);
        return userId;
    }
    //解析jwt(用户id和门店id)
    public static Map<String, Integer>parseJwtByUserIdAndStoreId(String token){
        Claims claims = parse(token);
        Integer userId = (Integer) claims.get(USER_ID_KEY);
        Integer storeId = (Integer) claims.get(STORE_ID_KEY);
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put(USER_ID_KEY,userId);
        map.put(STORE_ID_KEY,storeId);
        return map;
    }
    /**
     * 用户登录成功后生成Jwt
     * 使用Hs256算法
     *
     * @param expiredInMillis jwt过期时间
     * @param claims          保存在Payload（有效载荷）中的内容
     * @return token字符串
     */
    public static String create(long expiredInMillis, Map<String, Object> claims) {
        //指定签名的时候使用的签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        //生成JWT的时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //创建一个JwtBuilder，设置jwt的body
        JwtBuilder builder = Jwts.builder()
                //保存在Payload（有效载荷）中的内容
                .setClaims(claims)
                //iat: jwt的签发时间
                .setIssuedAt(now)
                //设置过期时间
                .setExpiration(new Date(nowMillis + expiredInMillis))
                //设置签名使用的签名算法和签名使用的秘钥
                .signWith(signatureAlgorithm, SIGNING_KEY);

        return builder.compact();
    }

    /**
     * 解析token，获取到Payload（有效载荷）中的内容，包括验证签名，判断是否过期
     *
     * @param token
     * @return
     */
    public static Claims parse(String token) {
        //得到DefaultJwtParser
        Claims claims = Jwts.parser()
                //设置签名的秘钥
                .setSigningKey(SIGNING_KEY)
                //设置需要解析的token
                .parseClaimsJws(token).getBody();
        return claims;
    }
}